package com.haveajob.bill.controller;

import com.haveajob.bill.entity.Bill;
import com.haveajob.bill.service.BillService;
import com.haveajob.common.message.MessageUtil;
import com.haveajob.employee.service.EmployeeService;
import com.haveajob.employer.entity.Employer;
import com.haveajob.employer.service.EmployerService;
import com.haveajob.orderinfo.entity.OrderInfo;
import com.haveajob.orderinfo.service.OrderInfoService;
import com.haveajob.recruitinfo.entity.Recruitinfo;
import com.haveajob.recruitinfo.service.RecruitinfoService;
import com.haveajob.user.entity.User;
import com.haveajob.user.service.UserService;
import com.haveajob.usermessage.entity.Usermessage;
import com.haveajob.usermessage.service.UsermessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("bill")
public class BillController {

    @Autowired
    private BillService billService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private EmployerService employerService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private UserService userService;

    @Autowired
    private RecruitinfoService recruitinfoService;

    @Autowired
    private UsermessageService usermessageService;

    //退还保证金
    @RequestMapping("backMoney")
    @ResponseBody
    public String backMoney(HttpServletRequest request){
        //获取用户的userId和用户类型
        int userId = Integer.parseInt(request.getParameter("userId"));
        int userType = Integer.parseInt(request.getParameter("userType"));

        int transactionId =userType==0?employeeService.selectEmployeeByUserId(userId).getId():employerService.selectEmployerByUserId(userId).getId();

        //获取当前日期
        Date today=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        //查到今天总订单数
        int todayOrder = billService.countTheDayOrder(sdf.format(today));
        //生成订单编号
        String no = OrderNo(todayOrder,sdf.format(today));


        //创建保证金退还账单
        Bill bill = new Bill();
        bill.setTransactionnumber(no);
        bill.setBilltype(4);
        bill.setBalanceorpayments("收入");
        bill.setAmount(BigDecimal.valueOf(499));
        bill.setTransactiontime(new Date());
        bill.setTransactionid(transactionId);
        bill.setTransactionrole(userType);
        bill.setReadmessage("未读");
        bill.setPayMoneyType("余额收入");

        int i = billService.backMoneyInsertBill(bill,userId);


        //修改用户金钱
        User user = userService.selectByPrimaryKey(userId);
        BigDecimal userMoney = user.getAccountbalance();
        userMoney = userMoney.add(BigDecimal.valueOf(499));
        user.setAccountbalance(userMoney);

        int j = userService.UserUpdate(user);

        return i>0&&j>0?"succ":"false";
    }


    //查询交易记录
    @RequestMapping("userBills")
    @ResponseBody
    public List<Bill> userBills(HttpServletRequest request){
        //获取用户的userid和用户类型
        int userId = Integer.parseInt(request.getParameter("userId"));
        int userType = Integer.parseInt(request.getParameter("userType"));

        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");

        int transactionId = userType==0?employeeService.selectEmployeeByUserId(userId).getId():employerService.selectEmployerByUserId(userId).getId();

        List<Bill> bills = billService.selectUserBills(transactionId,startDate,endDate);

//        if (userType==0){
//            List<Bill> employeeBill = billService.selectEmployeeOrderBills(transactionId,startDate,endDate);
//
//            for (int i=0;i<employeeBill.size();i++){
//                employeeBill.get(i).setBalanceorpayments("收入");
//            }
//
//            bills.addAll(employeeBill);
//
//
//        }

        return bills;
    }


    //雇主支付工人工资
    @RequestMapping("masterPayMoney")
    @ResponseBody
    public String masterPayMoney(HttpServletRequest request){
        //获取订单编号，用户类型，用户id
        int id = Integer.parseInt(request.getParameter("id"));
        int userType = Integer.parseInt(request.getParameter("userType"));
        int userId = Integer.parseInt(request.getParameter("userId"));
        int employerId =  userType==0?employeeService.selectEmployeeByUserId(userId).getId():employerService.selectEmployerByUserId(userId).getId();
        BigDecimal money = BigDecimal.valueOf(Double.parseDouble(request.getParameter("money")));

        //获取当前操作的订单
        OrderInfo orderInfo = orderInfoService.selectByPrimaryKey(id);

        try {
            if (orderInfo.getOrderstatus()==3){
                Recruitinfo recruitinfo = recruitinfoService.selectById(Integer.parseInt(orderInfo.getRecruitinfoid()));
                recruitinfo.setId(Integer.parseInt(orderInfo.getRecruitinfoid()));
                recruitinfo.setWorkfinish(new Date());
                int i = recruitinfoService.updateByPrimaryKeySelective(recruitinfo);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        //获取当前日期
        Date today=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        //查到今天总订单数
        int todayOrder = billService.countTheDayOrder(sdf.format(today));
        //生成订单编号
        String no = OrderNo(todayOrder,sdf.format(today));
        //插入账单信息
        Bill bill = new Bill();


        //获取雇主当前的工程预付款
        Double employerProjectMoney = employerService.selectEmployerById(employerId).getProjectMoney();
        //获取当前订单应该缴纳的工程预付款
        double thisOrderProjectMoney = 0;
        if (orderInfo.getPricingmethod()==1){
            Integer tempDayMoney = Integer.parseInt(orderInfo.getDaysalary().substring(0,orderInfo.getDaysalary().length()-1));
            Integer day = Integer.parseInt(orderInfo.getWorkcycle());
            thisOrderProjectMoney = tempDayMoney*day;
        }else if (orderInfo.getPricingmethod()==2){
            thisOrderProjectMoney = Double.parseDouble(orderInfo.getOrdertotalmoney());
        }



        if (thisOrderProjectMoney >= money.doubleValue()) {
            bill.setTransactionnumber(no);
            bill.setOrdernumber(orderInfo.getOrdernumber());
            bill.setBilltype(7);
            bill.setBalanceorpayments("收入");
            bill.setAmount(BigDecimal.valueOf(thisOrderProjectMoney - money.doubleValue()));
            bill.setTransactiontime(new Date());
            bill.setTransactionid(employerId);
            bill.setTransactionrole(userType);
            bill.setReadmessage("未读");
            bill.setPayMoneyType("工程款退回");
        }

        int i = 0;
        if (bill.getAmount().doubleValue()!=0){
           i = billService.insertBill(bill);
        }else {
            i = 1;
        }



        //修改订单状态
        orderInfo.setOrderstatus(5);
        if (orderInfo.getEmployeehopemoney()==null){
            orderInfo.setEmployeehopemoney(money.doubleValue());
        }else if (orderInfo.getRealWorkCycle()==null || orderInfo.getRealWorkCycle()==""){
            Long realDay1 = (new Date().getTime()-orderInfo.getStartworktime().getTime())/86400000;
            Integer realDay = realDay1.intValue();
            orderInfo.setRealWorkCycle(realDay.toString());
        }
        orderInfo.setHopePayMoneyTime(new Date());


        int j = 0;
        int z = 0;

        //获取工人用户信息
        User employeeUser = userService.selectEmployeeUserMoney(orderInfo.getEmployeeid());

        if (i>0){
            j = orderInfoService.updateByPrimaryKeySelective(orderInfo);
            BigDecimal employeeMoney = employeeUser.getAccountbalance();
            if (orderInfo.getOrderProjectSafeMoneyStatus()==0){
                employeeMoney = employeeMoney.add(money);
                bill.setTransactionnumber(OrderNo(todayOrder,sdf.format(today)));
                bill.setOrdernumber(orderInfo.getOrdernumber());
                bill.setBilltype(3);
                bill.setBalanceorpayments("收入");
                bill.setAmount(money);
                bill.setTransactiontime(new Date());
                bill.setTransactionid(orderInfo.getEmployeeid());
                bill.setTransactionrole(0);
                bill.setReadmessage("未读");
                bill.setPayMoneyType("工程预付款支付");
            }else {
                if (orderInfo.getRealWorkCycle()!="" && orderInfo.getRealWorkCycle()!=null){
                    int safeProjectMoney = 3;
                    try {
                        safeProjectMoney = Integer.parseInt(orderInfo.getRealWorkCycle())*3;
                    }catch (Exception e){
                        safeProjectMoney = 3;
                    }
                    if (safeProjectMoney==0){
                        safeProjectMoney = 3;
                    }
                    employeeMoney = employeeMoney.add(money.subtract(BigDecimal.valueOf(safeProjectMoney)));

                    //添加保险支出账单
                    bill.setTransactionnumber(OrderNo(todayOrder,sdf.format(today)));
                    bill.setOrdernumber(orderInfo.getOrdernumber());
                    bill.setBilltype(9);
                    bill.setBalanceorpayments("支出");
                    bill.setAmount(BigDecimal.valueOf(safeProjectMoney));
                    bill.setTransactiontime(new Date());
                    bill.setTransactionid(orderInfo.getEmployeeid());
                    bill.setTransactionrole(0);
                    bill.setReadmessage("未读");
                    bill.setPayMoneyType("意外险自动扣除");
                    billService.insertBill(bill);

                    bill.setTransactionnumber(OrderNo(todayOrder,sdf.format(today)));
                    bill.setBilltype(3);
                    bill.setBalanceorpayments("收入");
                    bill.setAmount(money);
                    bill.setReadmessage("未读");
                    bill.setPayMoneyType("工程预付款支付");
                }
            }

            int k = billService.insertBill(bill);

            employeeUser.setAccountbalance(employeeMoney);
            z = userService.UserUpdate(employeeUser);
        }

        if (thisOrderProjectMoney >= money.doubleValue()){
            Employer employer = employerService.selectEmployerById(employerId);
            employer.setId(employer.getUserid());
            employer.setProjectMoney(employerProjectMoney-thisOrderProjectMoney);
            employerService.UpdateEmployer(employer);


            double projectMoney = thisOrderProjectMoney - money.doubleValue();

            User user = userService.selectByPrimaryKey(userId);
            BigDecimal userMoney = BigDecimal.valueOf(0);

            try {
                userMoney = user.getAccountbalance();
            }catch (Exception e){
                userMoney = BigDecimal.valueOf(0);
            }
            user.setAccountbalance(userMoney.add(BigDecimal.valueOf(projectMoney)));
            int t = userService.UserUpdate(user);
        }

            //给工人添加消息通知
            EmployeeMessage(money.doubleValue(),orderInfo,5);



        return i>0&&j>0&&z>0?"succ":"false";
    }




    //生成账单编号方法
    public String OrderNo(int i,String d) {
        String No = "JY";
        String date = d.substring(0, 4) + d.substring(5, 7) + d.substring(8, 10);
        String number;

        if (i >= 0 && i < 10) {
            number = "000" + (i + 1);
        } else if (i > 9 && i < 100) {
            number = "00" + (i + 1);
        } else if (i > 99 && i < 1000) {
            number = "0" + (i + 1);
        } else {
            number = String.valueOf(i + 1);
        }

        No = No + date + number;
        return No;
    }




    public void EmployeeMessage(Double money,OrderInfo orderInfo,Integer messageType){
        Integer isOpen = employeeService.selectEmployeeDetail(orderInfo.getEmployeeid(),-1).getNotification();

        if (isOpen==0) {
            //发短息提示用户
            String phone = userService.selectEmployeePhone(orderInfo.getEmployeeid()).getRegisterphone();
            MessageUtil.sendMessageToUser(phone, messageType);
        }

        //创建新消息
        Usermessage usermessage = new Usermessage();
        usermessage.setMessagetype(messageType);
        usermessage.setMessagedate(new Date());
        usermessage.setMessageuserid(orderInfo.getEmployeeid());
        usermessage.setMessageusertype(0);
        usermessage.setMessageorderid(orderInfo.getId());
        usermessage.setMessageordernumber(orderInfo.getOrdernumber());
        usermessage.setMessageread(1);
        String RecruitinfoId = recruitinfoService.selectById(Integer.parseInt(orderInfo.getRecruitinfoid())).getRecruitid();
        usermessage.setRecruitinfoId(RecruitinfoId);
        usermessage.setMasterpaymoney(money);
       int i = usermessageService.insertSelective(usermessage);
    }


}
